﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;

namespace CarLeaseManageSystem
{
    public class CDbSetting
    {
        string connStr = "";
        OleDbDataAdapter adapter;
        OleDbConnection dbConn;
        OleDbCommand dbComm;
        DataSet dtSet;

        public CDbSetting()
        {
            string strDataBasePath = Application.StartupPath + "\\Files\\dbSetting.mdb";
            connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strDataBasePath;
            dbConn = new OleDbConnection(connStr);
        }
        /// <summary>
        /// 获取数据库连接字符串
        /// </summary>
        public string CONNStr
        {
            get { return connStr; }
        }
        /// <summary>
        /// 获取数据集
        /// </summary>
        /// <param name="seleStr">查询字符串</param>
        /// <returns>数据集</returns>
        public DataSet GetDataSet(string seleStr)
        {
            dtSet = new DataSet();
            adapter = new OleDbDataAdapter(seleStr, dbConn);
            adapter.Fill(dtSet);
            return dtSet;
        }
        /// <summary>
        /// 保存更新
        /// </summary>
        public void Save()
        {
            OleDbCommandBuilder build = new OleDbCommandBuilder(adapter);
            adapter.UpdateCommand = build.GetUpdateCommand();
            adapter.Update(dtSet.Tables[0]);
            dtSet.AcceptChanges();
        }
        /// <summary>
        /// 执行SQL语句
        /// </summary>
        /// <param name="sqlStr">SQL语句</param>
        /// <returns>受影响的行数</returns>
        public int ExecuteSql(string sqlStr)
        {
            try
            {
                dbComm = new OleDbCommand(sqlStr, dbConn);
                dbConn.Open();
                int i = dbComm.ExecuteNonQuery();
                dbConn.Close();
                return i;
            }
            catch { dbConn.Close(); return 0; }
        }
        /// <summary>
        /// 执行指定查询
        /// </summary>
        /// <param name="seleStr">sql查询语句</param>
        /// <returns>返回OleDbDataReader</returns>
        public OleDbDataReader Select(string seleStr)
        {
            try
            {
                OleDbCommand comm = new OleDbCommand(seleStr, dbConn);
                dbConn.Open();
                OleDbDataReader dataReader;
                dataReader = comm.ExecuteReader(CommandBehavior.CloseConnection);//当阅读关闭时关闭数据库连接
                return dataReader;
            }
            catch { dbConn.Close(); return null; }
        }
    }
}